﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.IO;
using InformationSystem.BLL.Core.Model;
using System.Threading;
using InformationSystem.Utility;
using System.Data;
using InformationSystem.BLL.Core.Service;

namespace InformationSystem.WebSite.UtilityPage
{
    public partial class SimpleDataImport : BasePage
    {

        public IStudentService StudentService { get; set; }
        protected LoginUser user;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = (LoginUser)Session["LoginUser"];

            if (!IsPostBack && !X.IsAjaxRequest)
            {
                if (Session["DataImportFileName"] == null)
                    Session.Add("DataImportFileName", string.Empty);
                if (Request.QueryString["m"] != null)
                {
                    int m = 0;
                    int.TryParse(Request.QueryString["m"], out  m);
                    if (m == 1)
                    {
                        cmbtype.SelectedIndex = 1;
                        comcon.Hidden = false;
                    }
                }
            }

        }


        protected void UploadClick(object sender, DirectEventArgs e)
        {
            if (this.fileUpLoad.HasFile)
            {
                //检测文件类型
                if (Path.GetExtension(this.fileUpLoad.PostedFile.FileName) == ".xls")
                {
                    //Server.MapPath;
                    string savePath = Path.Combine(Server.MapPath("~"), Common.UploadTemp);

                    string filename = Guid.NewGuid().ToString() + Path.GetExtension(fileUpLoad.PostedFile.FileName);
                    this.fileUpLoad.PostedFile.SaveAs(Path.Combine(savePath, filename));

                    if (Session["DataImportFileName"] != null && Session["DataImportFileName"].ToString() != string.Empty)
                    {
                        if (File.Exists(Path.Combine(savePath, Session["DataImportFileName"].ToString())))
                            File.Delete(Path.Combine(savePath, Session["DataImportFileName"].ToString()));
                    }
                    Session["DataImportFileName"] = filename;
                    X.Msg.Hide();
                    this.WizardPanel.ActiveIndex++;
                    probar.Render();
                    txtlog.Text = string.Format("[{0}]:文件上传成功，请点击导入.\r\n", DateTime.Now); ;
                    txtlog.Render();
                    fileUpLoad.Reset();
                }
                else
                {
                    X.Msg.Show(new MessageBoxConfig
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.ERROR,
                        Title = "错误",
                        Message = "上传的文件类型目前不支持,请确认是Excel文件，并关闭使用该文件的程序！"
                    });
                }
            }
        }


        protected void btnImport_Click(object sender, DirectEventArgs e)
        {
            this.Session["LongActionProgress"] = 0;
            this.Session["log"] = string.Empty;
            this.Session["successful"] = 1;
            ThreadPool.QueueUserWorkItem(ImportHandler);
            ResourceManager1.AddScript("{0}.startTask('importprogress');", taskmgr.ClientID);
            probar.UpdateProgress(0, "初始化...");
        }

        private void ImportHandler(object state)
        {
            //调用Excel Utility类读取列字段信息
            string savePath = Path.Combine(Server.MapPath("~"), Common.UploadTemp);
            if (Session["DataImportFileName"] != null && Session["DataImportFileName"].ToString() != string.Empty)
            {
                savePath = Path.Combine(savePath, Session["DataImportFileName"].ToString());
            }
            else
            {
                this.SetLog("文件信息丢失，请重新上传!");
                this.Session["successful"] = 0;
                this.Session.Remove("LongActionProgress");
                return;
            }
            TableScheme ts = ExcelUtility.ReadExcelScheme(savePath);
            if (ts == null)
            {
                this.SetLog("未能从Excel表格中读取有效信息！");
                this.Session["successful"] = 0;
                this.Session.Remove("LongActionProgress");
                return;
            }
            //根据不同类型检查字段
            if (cmbtype.SelectedIndex == 0)
            {
                //学生信息导入
                if (ts.FieldList.Find(val => val.FiledName == Common.Class) == null)
                {
                    this.SetLog(string.Format("Excel表格中没有 {0} 字段！", Common.Class));
                    this.Session["successful"] = 0;
                    this.Session.Remove("LongActionProgress");
                    return;
                }
                if (ts.FieldList.Find(val => val.FiledName == Common.StuID) == null)
                {
                    this.SetLog(string.Format("Excel表格中没有 {0} 字段！", Common.StuID));
                    this.Session["successful"] = 0;
                    this.Session.Remove("LongActionProgress");
                    return;
                }
                if (ts.FieldList.Find(val => val.FiledName == Common.Name) == null)
                {
                    this.SetLog(string.Format("Excel表格中没有 {0} 字段！", Common.Name));
                    this.Session["successful"] = 0;
                    this.Session.Remove("LongActionProgress");
                    return;
                }
                if (ts.FieldList.Find(val => val.FiledName == Common.Sex) == null)
                {
                    this.SetLog(string.Format("Excel表格中没有 {0} 字段！", Common.Sex));
                    this.Session["successful"] = 0;
                    this.Session.Remove("LongActionProgress");
                    return;
                }
                if (ts.FieldList.Find(val => val.FiledName == Common.MajorName) == null)
                {
                    this.SetLog(string.Format("Excel表格中没有 {0} 字段！", Common.MajorName));
                    this.Session["successful"] = 0;
                    this.Session.Remove("LongActionProgress");
                    return;
                }
                DataTable content = ExcelUtility.ReadExcel(savePath, ts.TableName);
                if (content == null)
                {
                    this.SetLog("Excel数据读取失败！");
                    this.Session["successful"] = 0;
                    this.Session.Remove("LongActionProgress");
                    return;
                }
                if (content.Rows.Count == 0)
                {
                    this.SetLog("Excel中没有有效数据！");
                    this.Session["successful"] = 0;
                    this.Session.Remove("LongActionProgress");
                    return;
                }
                Session["total"] = content.Rows.Count;
                StudentService.OnupdateProgress += new EventHandler(StudentService_OnupdateProgress);
                StudentService.Complete += new EventHandler(StudentService_Complete);
                StudentService.ImportStudentInfo(content, user);
            }
            else
            {
                //学生成绩导入
                int term = 0;
                int.TryParse(cmbterm.SelectedItem.Value, out term);
                if (term < 1 || term > 8)
                {
                    this.SetLog("学期信息错误！");
                    this.Session["successful"] = 0;
                    this.Session.Remove("LongActionProgress");
                    return;
                }
                Session["Term"] = term;
                if (ts.FieldList.Find(val => val.FiledName == Common.CourseID) == null)
                {
                    this.SetLog(string.Format("Excel表格中没有 {0} 字段！", Common.CourseID));
                    this.Session["successful"] = 0;
                    this.Session.Remove("LongActionProgress");
                    return;
                }
                if (ts.FieldList.Count < 3)
                {
                    this.SetLog("Excel表格中没有要导入的成绩字段！");
                    this.Session["successful"] = 0;
                    this.Session.Remove("LongActionProgress");
                    return;
                }

                DataTable content = ExcelUtility.ReadExcel(savePath, ts.TableName);
                if (content == null)
                {
                    this.SetLog("Excel数据读取失败！");
                    this.Session["successful"] = 0;
                    this.Session.Remove("LongActionProgress");
                    return;
                }
                if (content.Rows.Count == 0)
                {
                    this.SetLog("Excel中没有有效数据！");
                    this.Session["successful"] = 0;
                    this.Session.Remove("LongActionProgress");
                    return;
                }
                Session["total"] = content.Rows.Count;
                StudentService.OnupdateProgress += new EventHandler(StudentService_OnupdateProgress);
                StudentService.Complete += new EventHandler(StudentService_Complete);
                StudentService.ImportStudentMark(content, (int)Session["Term"]);
            }
        }

        void StudentService_Complete(object sender, EventArgs e)
        {
            this.SetLog("任务完成！");
            this.Session["successful"] = 1;
            this.Session.Remove("LongActionProgress");

        }

        void StudentService_OnupdateProgress(object sender, EventArgs e)
        {
            MyEventArgs me = (MyEventArgs)e;
            this.Session["LongActionProgress"] = me.Current;
            if (me.HasMsg)
                this.SetLog(me.Msg);
        }

        private void SetLog(string log)
        {
            lock (this.Session["log"])
            {
                this.Session["log"] += string.Format("[{0}]: {1}\r\n", DateTime.Now, log);
            }
        }

        private string GetLog()
        {
            string log = string.Empty;
            lock (this.Session["log"])
            {
                log = this.Session["log"].ToString();
                this.Session["log"] = string.Empty;
            }
            return log;
        }

        protected void RefreshProgress(object sender, DirectEventArgs e)
        {
            object progress = this.Session["LongActionProgress"];

            if (progress != null)
            {
                if ((int)progress != 0)
                {
                    float cu = (float)(int)progress;
                    float total = (float)(int)Session["total"];
                    float rate = cu / total;
                    probar.UpdateProgress(rate, string.Format("{0}%", (rate * 100).ToString("##")));
                }
            }
            else
            {
                ResourceManager1.AddScript("{0}.stopTask('importprogress');", taskmgr.ClientID);
                probar.UpdateProgress(1, (int)this.Session["successful"] == 1 ? "任务完成!" : "任务失败！");
            }
            txtlog.Text += this.GetLog();
        }




        protected override bool CommitPermissionCheck()
        {
            throw new NotImplementedException();
        }
    }


}